import React, { Component } from 'react'
import InputField from './InputField'
import { Checkbox, Button } from 'antd';
import { withRouter } from 'react-router-dom'
import { message } from 'antd';
import { _login } from '../common/Api';
import cookies from 'react-cookies'
import '../../componentStyle/Register.scss'
import md5 from 'md5'

const error = (msg) => {
    message.error(msg);
};

const success = () => {
    message.success('登录成功');
};

class Register extends Component {
    constructor(props) {
        super(props);
        this.state = {
            // 表单信息，为静态
            form: [
                {
                    placeholder: '请输入用户名',
                    icon: "anticonyonghu",
                    nullTip: '输入不能为空',
                    errorTip: '请输入英文作为你的用户名',
                    pattern: /[a-zA-Z]/,
                    isPassword: false,
                    type: 'username',
                    method: 'register'
                },
                {
                    placeholder: '请输入至少6位密码',
                    icon: "anticonziyuanxhdpi",
                    nullTip: '输入不能为空',
                    errorTip: '密码不能少于6位且不能包括中文',
                    pattern: /\w{6,}/,
                    isPassword: true,
                    type: 'password',
                    method: 'register'
                }
            ],
            // 用户输入的信息，用于保存以便验证
            // 依次为用户名与密码
            verifyObj: [
                {}, {}
            ]
        }
    }

    // 接收InputField的数据
    handleTransformData = (data) => {
        let { verifyObj } = this.state;
        if (data.type === "username") {
            verifyObj[0] = data;
            this.setState({
                verifyObj
            });
        } else {
            verifyObj[1] = data;
            this.setState({
                verifyObj
            });
        }
    }

    // 以下两个函数实现页面hover功能
    handleMouseover = () => {
        this.elem.style.backgroundColor = 'rgba(255, 255, 255, 0.4)';
    }

    handleMouseout = () => {
        this.elem.style.backgroundColor = 'rgba(255, 255, 255, 0.3)';
    }

    // 处理登录按钮
    hanleClick = () => {
        // 遍历查找verifyResult，如果全部为真，则传到后端进行用户验证
        const { verifyObj } = this.state;
        let count = 0; // 错误计数器
        verifyObj.map((item, index) => {
            if (!item.verifyResult) {
                count++;
            }
            return index;
        })
        if (count) {
            error('格式错误');
            return;
        }

        this.getLoginUser(verifyObj[0].value, md5(verifyObj[1].value))
    }

    // 登录接口
    async getLoginUser(username, password) {
        let obj = {};
        obj.key = username;
        obj.password = password;

        const res = await _login(obj);

        if (res.data.code === 0) {
            // 向redux传递用户信息
            this.props.transform_user(res.data.data)

            // 使用cookie存放token
            cookies.save('Authorization', res.data.data.token)

            // 提示成功信息
            success();

            // 跳转到首页
            this.props.history.push("/home");
        } else {
            error('用户名或密码错误');
        }
    }

    enterEnroll = () => {
        this.props.enterEnroll();
    }

    render() {
        return (
            <div style={{
                width: 400,
                height: 600,
                position: 'relative',
            }}>
                <div style={{
                    backgroundColor: 'rgba(33, 33, 33, 0.3)',
                    height: 400,
                    borderRadius: 5
                }}>
                    <div style={{
                        width: 350,
                        margin: '0 auto',
                        paddingTop: 20,
                        display: 'flex',
                        justifyContent: 'space-between',
                        paddingBottom: 20
                    }}>
                        <div style={{
                            color: '#fff',
                            width: 150,
                            textAlign: 'center',
                            fontSize: 30,
                            borderBottom: '3px solid white',
                            paddingBottom: 10,
                            cursor: 'pointer'
                        }}>登录</div>
                        <div style={{
                            color: '#ddd',
                            width: 150,
                            textAlign: 'center',
                            fontSize: 30,
                            paddingBottom: 10,
                            cursor: 'pointer'
                        }} onClick={this.enterEnroll}>注册</div>
                    </div>
                    <InputField data={this.state.form[0]} transfornFun={this.handleTransformData} />
                    <InputField data={this.state.form[1]} transfornFun={this.handleTransformData} />
                    <div style={{
                        display: 'flex',
                        justifyContent: 'space-between',
                        marginLeft: 25,
                        marginRight: 25
                    }}>
                        <Checkbox style={{
                            marginTop: 0,
                            marginBottom: 20,
                        }}>
                            <span style={{
                                color: '#fff',
                                fontSize: 18
                            }}>
                                记住密码
                            </span>
                        </Checkbox>
                        <div style={{
                            color: '#fff',
                            fontSize: 18
                        }}>
                            忘记密码？
                        </div>
                    </div>
                    <Button type="primary" style={{
                        marginLeft: 25,
                        width: 350,
                        height: 40,
                        fontSize: 20
                    }} onClick={() => this.hanleClick()}>登录</Button>
                </div>
            </div>
        )
    }
}

export default withRouter(Register);